package fhp.hlhj.giantfold.utils

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager

/**
 * author: FHP
 * data: on 2017\11\22 0022 17:58
 * E-Mail: 103945089@qq.com
 */

class ShakeUtils(context: Context) : SensorEventListener {

    private var mSensorManager: SensorManager? = null
    private var mOnShakeListener: OnShakeListener? = null

    init {
        mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    }

    fun setOnShakeListener(onShakeListener: OnShakeListener) {
        mOnShakeListener = onShakeListener
    }

    fun onResume() {
        mSensorManager!!.registerListener(this,
                mSensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL)
    }

    fun onPause() {
        mSensorManager!!.unregisterListener(this)
    }

    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {

    }

    override fun onSensorChanged(event: SensorEvent) {
        val sensorType = event.sensor.type
        //values[0]:X轴，values[1]：Y轴，values[2]：Z轴
        val values = event.values
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            //这里可以调节摇一摇的灵敏度
            if (Math.abs(values[0]) > SENSOR_VALUE || Math.abs(values[1]) > SENSOR_VALUE || Math.abs(values[2]) > SENSOR_VALUE) {
                println("sensor value == " + " " + values[0] + " " + values[1] + " " + values[2])
                if (null != mOnShakeListener) {
                    mOnShakeListener!!.onShake()
                }
            }
        }
    }

    interface OnShakeListener {
        fun onShake()
    }

    companion object {
        private val SENSOR_VALUE = 14
    }
}